/*
 * Copyright 2009-2010 Nanjing RedOrange ltd (http://www.red-orange.cn)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package redora.client.mvp;

import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
import redora.client.Persistable;
import redora.client.Persistable.Scope;

import static redora.client.mvp.ServiceBase.FINDER_PARAM;
import static redora.client.mvp.ServiceBase.PARAM_PARAM;

public class FindEvent extends GwtEvent<FindEvent.Handler> {
    public static GwtEvent.Type<FindEvent.Handler> TYPE = new GwtEvent.Type<FindEvent.Handler>();

    public interface Handler extends EventHandler {
        void onSuccess(FindEvent event);
    }

    public final String finderKey;
    public final Long[] results;
    public final Class<? extends Persistable> cls;
    public final Scope scope;
    public final int step;
    public boolean hasMore;

    public FindEvent(Class<? extends Persistable> cls, String finderKey, Scope scope, Long[] results, int step, boolean hasMore) {
        this.cls = cls;
        this.finderKey = finderKey;
        this.scope = scope;
        this.results = results;
        this.step = step;
        this.hasMore = hasMore;
    }

    public boolean wasMe(Class<? extends Persistable> cls, String finderKey) {
        return this.cls.equals(cls) && this.finderKey.equals(finderKey);
    }

    public int finder() {
        String _p = param(FINDER_PARAM);
        return _p == null ? -1 : Integer.parseInt(_p);
    }

    public Long paramId() {
        String _p = param(PARAM_PARAM);
        return _p == null ? null : Long.parseLong(_p);
    }

    String param(String key) {
        if (finderKey.contains(key)) {
            String _p = finderKey.substring(finderKey.indexOf(key) + key.length());
            if (_p.contains("&")) {
                _p = _p.substring(0, _p.indexOf("&"));
            }
            return _p;
        }
        return null;
    }

    public String param() {
        return param(PARAM_PARAM);
    }


    @Override
    public GwtEvent.Type<FindEvent.Handler> getAssociatedType() {
        return TYPE;
    }

    @Override
    protected void dispatch(FindEvent.Handler handler) {
        handler.onSuccess(this);
    }
}
